package auction.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {
	
	private static ReceiverThread serverReceiver;
	
	private static Socket serverSocket;

	private static BufferedReader ins;

	private static PrintWriter serverOut;

	/*
	 * list of auctions received from server after !list
	 */
	private static String[] auctionList = new String[0];
	
	private static int serverPort;
	private static int clientPort;
	private static String serverHost;

	public static void main(String[] args) {
		/* check arguments */
		boolean correctArgs = args.length == 3 && args[1].matches("[0-9]+")
				&& args[2].matches("[0-9]+");
		if (correctArgs) {
			serverHost = args[0];
			serverPort = Integer.parseInt(args[1]);
			clientPort = Integer.parseInt(args[2]);

			correctArgs = correctArgs && serverPort > 0 && serverPort < 65536;
			correctArgs = correctArgs && clientPort > 0
					&& clientPort < 65536;
			correctArgs = correctArgs && args[0].length() > 0;
		}
		if (!correctArgs) {
			System.err
					.println("Usage: java auction.client.Client <server host> <server port> <client port>");
			System.exit(1);
		}
		

		try {
			serverSocket = new Socket(serverHost, serverPort);
			
			(serverReceiver = new ReceiverThread(serverSocket))
					.start();
			ins = new BufferedReader(new InputStreamReader(System.in));
			serverOut = new PrintWriter(new OutputStreamWriter(serverSocket
					.getOutputStream()), true);

			
		} catch (IOException e) {
			System.err.println("Error while initialization: " + e.getMessage());
			cleanUp(1);
		}

	

		while (true) {
			
			String input = "";
			try {
						
				input = ins.readLine();

			} catch (Exception e) {
				System.err.println("Error while processing input: "
						+ e.getMessage());
				cleanUp(1);
			}
			
			serverOut.println(input+";"+clientPort);		

		}

	}

	public static void cleanUp(int ret) {
		
		if (serverReceiver != null) {
			serverReceiver.cleanUp();
		}
		try {
			if (serverOut != null) {
				serverOut.close();
			}
			if (serverSocket != null) {
				serverSocket.close();
			}
		} catch (IOException e) {
			/* ignore */
		}
		System.exit(ret);
	}


	public static void printAuctionList(String string) {
		//System.out.println("Available auctions:");
		synchronized (auctionList) {
			auctionList = string.split(";");
			
			for (int a = 0; a < auctionList.length; a++) {
				if(!auctionList[a].equals(""))
					System.out.println(auctionList[a] + " ");
			
			}
		}
	}

}
